package Day2;

/**
 * @author ：Yan Guang
 * @date ：Created in 2020/4/27 19:03
 * @description：自我练习
 */
class Product {
        private int ProductNum;
    public synchronized void addProucts() {
        while (true){
            if (ProductNum<20){
                ProductNum++;
                System.out.println(Thread.currentThread().getName()+ProductNum);
                notify();
            }else {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public synchronized void costProducts() {
        while (true){
            if (ProductNum>0){
                System.out.println(Thread.currentThread().getName()+ProductNum);
                ProductNum--;
                notify();
            }else {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class Producter extends Thread {
    private Product product;

    public Producter(Product product) {
        this.product = product;
    }

    @Override
    public void run() {
        product.addProucts();
    }
}

class Customr extends Thread {
    private Product product;

    public Customr(Product product) {
        this.product = product;
    }

    @Override
    public void run() {
        product.costProducts();
    }
}

public class Productagain {
    public static void main(String[] args) {
        Product product=new Product();
        Producter p1 = new Producter(product);
        Customr c1 = new Customr(product);

        p1.setName("生产者");
        c1.setName("消费者");

        p1.start();
        c1.start();
    }
}
